// 虚拟摇杆控制
class Joystick {
    constructor(inputSystem) {
        this.inputSystem = inputSystem;
        this.container = null;
        this.knob = null;
        this.active = false;
        this.touchId = null;
        this.centerX = 0;
        this.centerY = 0;
        this.maxDistance = 0;
        this.isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        
        // 只在触摸设备上初始化事件监听
        if (this.isTouchDevice) {
            this.addEventListeners();
        }
    }
    
    init(x, y) {
        // 创建虚拟摇杆容器
        this.container = document.createElement('div');
        this.container.className = 'joystick-container';
        
        // 创建摇杆按钮
        this.knob = document.createElement('div');
        this.knob.className = 'joystick-knob';
        
        // 设置摇杆容器的位置
        this.container.style.left = `${x - 60}px`; // 60是容器宽度的一半
        this.container.style.top = `${y - 60}px`;
        
        // 添加到DOM
        this.container.appendChild(this.knob);
        document.body.appendChild(this.container);
        
        // 计算摇杆中心位置
        this.centerX = x;
        this.centerY = y;
        this.maxDistance = 60; // 设置最大移动距离为容器半径
    }
    
    addEventListeners() {
        // 监听整个文档的触摸开始事件
        document.addEventListener('touchstart', (e) => {
            // 检查触摸点是否在屏幕下3/4区域内
            const touchY = e.touches[0].clientY;
            const screenHeight = window.innerHeight;
            if (touchY < screenHeight * 0.25) return; // 如果在上1/4区域则不响应
            if (!this.active) {
                this.active = true;
                this.touchId = e.changedTouches[0].identifier;
                // 在触摸点位置初始化摇杆
                this.init(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
                this.updateJoystickPosition(e.changedTouches[0]);
                e.preventDefault();
            }
        }, { passive: false });
        
        // 摇杆触摸移动
        document.addEventListener('touchmove', (e) => {
            if (this.active) {
                for (let i = 0; i < e.changedTouches.length; i++) {
                    if (e.changedTouches[i].identifier === this.touchId) {
                        this.updateJoystickPosition(e.changedTouches[i]);
                        e.preventDefault();
                        break;
                    }
                }
            }
        }, { passive: false });
        
        // 摇杆触摸结束
        document.addEventListener('touchend', (e) => {
            if (this.active) {
                for (let i = 0; i < e.changedTouches.length; i++) {
                    if (e.changedTouches[i].identifier === this.touchId) {
                        this.active = false;
                        this.resetInput();
                        // 移除摇杆
                        if (this.container) {
                            document.body.removeChild(this.container);
                            this.container = null;
                            this.knob = null;
                        }
                        e.preventDefault();
                        break;
                    }
                }
            }
        }, { passive: false });
        
        // 摇杆触摸取消
        document.addEventListener('touchcancel', (e) => {
            if (this.active) {
                for (let i = 0; i < e.changedTouches.length; i++) {
                    if (e.changedTouches[i].identifier === this.touchId) {
                        this.active = false;
                        this.resetInput();
                        // 移除摇杆
                        if (this.container) {
                            document.body.removeChild(this.container);
                            this.container = null;
                            this.knob = null;
                        }
                        e.preventDefault();
                        break;
                    }
                }
            }
        }, { passive: false });
        

        // 监听窗口大小变化，重新计算摇杆位置
        window.addEventListener('resize', () => {
            if (this.container) {
                const containerRect = this.container.getBoundingClientRect();
                this.centerX = containerRect.left + containerRect.width / 2;
                this.centerY = containerRect.top + containerRect.height / 2;
                this.maxDistance = containerRect.width / 2;
            }
        });
    }
    
    updateJoystickPosition(touch) {
        // 计算触摸点与摇杆中心的距离
        const containerRect = this.container.getBoundingClientRect();
        this.centerX = containerRect.left + containerRect.width / 2;
        this.centerY = containerRect.top + containerRect.height / 2;
        
        const dx = touch.clientX - this.centerX;
        const dy = touch.clientY - this.centerY;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 限制摇杆移动范围
        let x, y;
        if (distance > this.maxDistance) {
            const angle = Math.atan2(dy, dx);
            x = this.centerX + Math.cos(angle) * this.maxDistance;
            y = this.centerY + Math.sin(angle) * this.maxDistance;
        } else {
            x = touch.clientX;
            y = touch.clientY;
        }
        
        // 更新摇杆位置
        this.knob.style.left = `${x - containerRect.left}px`;
        this.knob.style.top = `${y - containerRect.top}px`;
        
        // 更新输入状态
        this.updateInput(dx, dy);
    }
    
    resetJoystick() {
        // 重置摇杆位置
        this.knob.style.left = '50%';
        this.knob.style.top = '50%';
    }
    
    updateInput(dx, dy) {
        // 根据摇杆位置更新输入状态
        const deadZone = 10; // 死区，防止轻微触摸导致移动
        
        // 重置所有方向
        this.resetInput();
        
        // 根据摇杆位置设置方向
        if (Math.abs(dx) > deadZone || Math.abs(dy) > deadZone) {
            // 确定主要方向（水平或垂直）
            if (Math.abs(dx) > Math.abs(dy)) {
                // 水平方向为主
                if (dx > 0) {
                    this.inputSystem.touchInput.right = true;
                } else {
                    this.inputSystem.touchInput.left = true;
                }
            } else {
                // 垂直方向为主
                if (dy > 0) {
                    this.inputSystem.touchInput.down = true;
                } else {
                    this.inputSystem.touchInput.up = true;
                }
            }
        }
    }
    
    resetInput() {
        // 重置所有方向输入
        this.inputSystem.touchInput.up = false;
        this.inputSystem.touchInput.down = false;
        this.inputSystem.touchInput.left = false;
        this.inputSystem.touchInput.right = false;
    }
}

// 如果在浏览器环境中，将Joystick添加到window对象
if (typeof window !== 'undefined') {
    window.Joystick = Joystick;
}